package com.erpanderp.wam.usm.view.user;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.el.ELContext;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.primefaces.event.FlowEvent;

import com.erpanderp.wam.adm.view.UserMenuBean;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.PassportAndPANDetails;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.usm.model.service.user.WAMUserDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;
import com.erpanderp.wam.util.WAMPasswordUtil;

@ManagedBean
@ViewScoped
public class LoginBean implements Serializable {
	private static final long serialVersionUID = 1L;
	HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	ServletContext context = (ServletContext) FacesContext.getCurrentInstance()
			.getExternalContext().getContext();
	private WAMUser wamUser = new WAMUser();
	boolean USER_VALID;
	private boolean EMAIL_VALID;
	private boolean EMAIL_REGISREDORNOT;
	private EmailUtil emailUtil;
	private String EMAIL_MESSAGE;
	private String emailId;
	WAMUserDAO wamUserDAO = new WAMUserDAO();
	private Employee employee;
	private String stepToGo;
	private List<Employee> registeredEmployeesList = new ArrayList<Employee>();
	private EmployeeDAO employeeDAO = new EmployeeDAO();
	private Map<String, String> paramsMap;
	
	public LoginBean() {
		System.out.println("Initializing...");
		registeredEmployeesList = employeeDAO.getAllEmployees();

		if (registeredEmployeesList != null
				&& registeredEmployeesList.size() > 0) {
			System.out.println("EMPLOYEES ARE REGISTERED ALREADY");

			// FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/login.html");
			ValidationUtil.redirect();

		} else {
			try {
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("/wam/usm/user/registeradmin.html");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public void handleClose(CloseEvent event) {
		setEmailId("");
	}

	public void sendEmialAction() {
		validateEmail();

		System.out.println("EMAIL_VALID = " + EMAIL_VALID);

		if (EMAIL_VALID) {
			employee = wamUserDAO.getEmployeeByEmail(emailId);
			if (employee != null) {
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								" Password sent successfully.", ""));
				RequestContext.getCurrentInstance().execute(
						"forgotpasswordDialog.hide();");
				try {
					String EMAIL_MESSAGE = sendMessage();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				RequestContext.getCurrentInstance().execute(
						"forgotpasswordDialog.show();");
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								" Entered email is not registered with WAM .",
								""));
			}

		} else {
			System.out.println("EMAIL ID IS EMPTY");
			// FacesContext.getCurrentInstance().addMessage(null, new
			// FacesMessage(FacesMessage.SEVERITY_INFO," Enter Your WAM - Email ID .",
			// ""));
			RequestContext.getCurrentInstance().execute(
					"forgotpasswordDialog.show();");
		}
	}

	public String login() {
		validateUser();
		if (USER_VALID) {
			System.out.println(session.isNew());
			session.setAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER,
					wamUser);
			session.setAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSERNAME,
					wamUser.getEmployee().getFirstName());
			
			
			System.out.println("PARAMS: " + (Map<String, String>) session.getAttribute("PARAMS_MAP"));
			System.out.println("PARAMS: " + getParamsMap());
	        
			return "wudashboard";
		} else {
			return null;
		}
	}

	public void validateEmail() {

		EMAIL_VALID = true;

		if (ValidationUtil.isEmpty((emailId != null) ? emailId : null,
				"Email Id", null, FacesContext.getCurrentInstance()) != null) {
			EMAIL_VALID = false;
			System.out.println("FORM-VLD: " + EMAIL_VALID);
		}
	}

	// SENDING EMAIL
	public String sendMessage() throws Exception {

		wamUser = wamUserDAO
				.getPasswordByEmployeeId(employee.getEmployeeCode());

		emailUtil = new EmailUtil();
		Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);

		if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
			String[] to = { employee.getEmail() };
			emailUtil.setRecieverAddresses(to);
		} else {
			String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
			emailUtil.setRecieverAddresses(to);
		}

		String messageString = "Dear " + employee.getFirstName() + " "
				+ employee.getLastName() + "" + ",<br /><br />" +

				"<b>Your current Employee Id and Password are given below :</b><br/><br/>"
				+ "<table style='border: 1px solid #d9d9d9;'>"
				+ "<tr> <td>Employee Id </td><td> : </td><td>"
				+ employee.getEmployeeCode() + " </td></tr>"
				+ "<tr> <td>Password</td><td> : </td> <td>"
				+ WAMPasswordUtil.decrypt(wamUser.getPassword()) + " </td></tr>" + "</table><br/>" +

				"Thanks & Regards, <br />" + CommonLookup.WAM_DEVTEAM_SIGNATURE;
		;

		emailUtil.setMessage(messageString);
		emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
		emailUtil.setSubject("WAM - Forgot password information for "
				+ employee.getFirstName() + " " + employee.getLastName());

		SwingWorker worker = new SwingWorker<String, Object>() {
			@Override
			protected String doInBackground() throws Exception {
				EMAIL_MESSAGE = emailUtil.processAndSendEmail();
				return null;
			}

			@Override
			protected void done() {
				System.out.println("DONE " + EMAIL_MESSAGE);
			}
		};
		worker.execute();
		System.out.println("BEFORE RETURNING: " + EMAIL_MESSAGE);
		return EMAIL_MESSAGE;
	}

	public void validateUser() {
		USER_VALID = true;

		if (ValidationUtil.isEmpty(wamUser.getEmployeeCode(), "Employee ID",
				"", FacesContext.getCurrentInstance()) != null) {
			USER_VALID = false;
		}

		if (ValidationUtil.isEmpty(wamUser.getPassword(), "Password", "",
				FacesContext.getCurrentInstance()) != null) {
			USER_VALID = false;
		}

		if (USER_VALID) {
			WAMUser tempWAMUser = null;
			if ((tempWAMUser = wamUserDAO.validateWAMUser(
					wamUser.getEmployeeCode(), wamUser.getPassword())) != null) {
				wamUser = tempWAMUser;
				wamUser.setLOGGED_IN(true);
			} else if((tempWAMUser = wamUserDAO.wamUserExistense(
					wamUser.getEmployeeCode(), wamUser.getPassword())) != null) {
				USER_VALID = false;
				FacesContext.getCurrentInstance().addMessage(
						"",
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Your WAM account has been deactivated.", ""));
				wamUser.setLOGGED_IN(false);
			}else{
				USER_VALID = false;
				FacesContext.getCurrentInstance().addMessage(
						"",
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Username and password does not match.", ""));
				wamUser.setLOGGED_IN(false);
			}
		}
	}

	public void forgotpassword() {

	}

	public void validateUserforforgetpassword() {
		USER_VALID = true;

		if (ValidationUtil.isEmpty(wamUser.getEmployeeCode(), "Employee ID",
				"", FacesContext.getCurrentInstance()) != null) {
			USER_VALID = false;
		}
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String getStepToGo() {
		return stepToGo;
	}

	public void setStepToGo(String stepToGo) {
		this.stepToGo = stepToGo;
	}

	public boolean isEMAIL_REGISREDORNOT() {
		return EMAIL_REGISREDORNOT;
	}

	public void setEMAIL_REGISREDORNOT(boolean eMAIL_REGISREDORNOT) {
		EMAIL_REGISREDORNOT = eMAIL_REGISREDORNOT;
	}

	public List<Employee> getRegisteredEmployeesList() {
		return registeredEmployeesList;
	}

	public void setRegisteredEmployeesList(
			List<Employee> registeredEmployeesList) {
		this.registeredEmployeesList = registeredEmployeesList;
	}

	public boolean isEMAIL_VALID() {
		return EMAIL_VALID;
	}

	public void setEMAIL_VALID(boolean eMAIL_VALID) {
		EMAIL_VALID = eMAIL_VALID;
	}

	public static boolean isLoggedIn() {
	    HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	    if(session != null){
	    	return (session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER) != null);	
	    }else{
	    	return false;
	    }	    
	}

	public Map<String, String> getParamsMap() {
		return paramsMap;
	}

	public void setParamsMap(Map<String, String> paramsMap) {
		
		this.paramsMap = paramsMap;

	    if(session != null){
	    	System.out.println("Setting attributes: " + paramsMap);
	    	if (session.getAttribute("PARAMS_MAP") == null)
	    		session.setAttribute("PARAMS_MAP", paramsMap);	
	    	System.out.println("S" + session.getAttribute("PARAMS_MAP"));
	    }
	} 
	
}
